package com.googlecode.publicholiday.repository;

import com.googlecode.publicholiday.repository.jdbc.JdbcPublicHolidayRepository;
import org.joda.time.LocalDate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import javax.sql.DataSource;
import java.sql.Date;

@Repository
public class SpringJdbcPublicHolidayRepository extends SpringJdbcImmutablePublicHolidayRepository implements MutablePublicHolidayRepository {

    private final static String DELETE_PUBLIC_HOLIDAY_SQL = "DELETE public_holiday WHERE country_code = ? AND holiday_date = ?";
    private final static String INSERT_PUBLIC_HOLIDAY_SQL = "INSERT INTO public_holiday ( country_code, holiday_date ) VALUES ( ?, ? )";
    private final static Logger LOG = LoggerFactory.getLogger(JdbcPublicHolidayRepository.class);

    public SpringJdbcPublicHolidayRepository(DataSource dataSource) {
        super(dataSource);
    }

    @Override
    public boolean create(String countryCode, LocalDate holidayDate) {
        boolean insertRequired = find(countryCode, holidayDate) == null;
        if (insertRequired) {
            LOG.debug("Attempting to create a Public Holiday in: {} on: {}", countryCode, holidayDate);
            jdbcTemplate.update(getCreatePublicHolidaySqlStatement(), countryCode, new Date(holidayDate.toDate().getTime()));
        } else {
            LOG.debug("Public Holiday already exists in: {} on: {}", countryCode, holidayDate);
        }
        return insertRequired;
    }

    protected String getCreatePublicHolidaySqlStatement() {
        return INSERT_PUBLIC_HOLIDAY_SQL;
    }

    @Override
    public boolean delete(String countryCode, LocalDate holidayDate) {
        LOG.debug("Attempting to delete a Public Holiday in: {} on: {}", countryCode, holidayDate);
        return jdbcTemplate.update(getDeletePublicHolidaySqlStatement(), countryCode, new Date(holidayDate.toDate().getTime())) == 1;
    }

    protected String getDeletePublicHolidaySqlStatement() {
        return DELETE_PUBLIC_HOLIDAY_SQL;
    }
}
